package de.negativrekord.blockworld;

import cc.creativecomputing.graphics.CCDrawMode;
import cc.creativecomputing.graphics.CCGraphics;
import cc.creativecomputing.graphics.shader.CCGLSLShader;
import cc.creativecomputing.graphics.shader.CCShaderBuffer;
import cc.creativecomputing.graphics.texture.CCTexture.CCTextureTarget;
import cc.creativecomputing.graphics.texture.CCTexture2D;
import cc.creativecomputing.io.CCIOUtil;
import cc.creativecomputing.math.CCVector3f;
import cc.creativecomputing.math.CCVector4f;

public class KnnClassifier {

	int cnt = 0;
	int nPrototypes = 100;
	
	private CCVector4f[] prototypes = new CCVector4f[nPrototypes];
	private CCGLSLShader shader;
	private CCGLSLShader initValueShader;
	private CCShaderBuffer  prototypeBuffer;
	
	public KnnClassifier () {
		
		for (int i=0; i<nPrototypes; i++) {
			prototypes[i] = new CCVector4f(0,0,0,-1);
		}
		
		prototypeBuffer = new CCShaderBuffer (32, 3, 4, nPrototypes, 2, 
											  CCTextureTarget.TEXTURE_RECT);
		
		
		shader = new CCGLSLShader (
				CCIOUtil.classPath (this, "shader/knn_vp.glsl"),
				CCIOUtil.classPath (this, "shader/knn_fp.glsl"));
		shader.load();
		
		initValueShader = new CCGLSLShader (
				null,
				CCIOUtil.classPath (this, "shader/init_fp.glsl"));
		initValueShader.load();
	}	
	
	public CCTexture2D centers() {
		return prototypeBuffer.attachment(0);
	}
	
	public void clearPrototypes() {
		cnt = 0;
	}
	public void addPrototype (CCVector3f p, float c) {
		prototypes[cnt] = new CCVector4f(p,c);
		cnt = (cnt+1)%nPrototypes;
	}
	
	public CCVector4f[] centersCPU() {
		return prototypes;
	}
	
	public void init (CCGraphics g) {
		initValueShader.start();
		
		prototypeBuffer.beginDraw();
		g.beginShape(CCDrawMode.POINTS);
		for (int i=0; i<nPrototypes; i++) {
			g.textureCoords (prototypes[i].x, prototypes[i].y, prototypes[i].z);
			g.vertex(0.5f+i,0.5f);
			g.textureCoords (prototypes[i].w, 0, 0);
			g.vertex(0.5f+i,1.5f);
		}
		g.endShape();
		prototypeBuffer.endDraw();
		
		initValueShader.end();
	}
}
